package top.huhuiyu.springboot.study.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.huhuiyu.springboot.study.base.BaseDataResult;
import top.huhuiyu.springboot.study.base.BaseResult;
import top.huhuiyu.springboot.study.base.PageBean;
import top.huhuiyu.springboot.study.base.PageResult;
import top.huhuiyu.springboot.study.entity.SoftwareType;
import top.huhuiyu.springboot.study.mapper.SoftwareMapper;
import top.huhuiyu.springboot.study.mapper.SoftwareTypeMapper;
import top.huhuiyu.springboot.study.service.SoftwareTypeService;

import java.util.List;

/**
 * @author 胡辉煜
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SoftwareTypeServiceImpl implements SoftwareTypeService {
  private final SoftwareTypeMapper softwareTypeMapper;
  private final SoftwareMapper softwareMapper;

  @Override
  public BaseResult insert(SoftwareType softwareType) {
    // 先验证软件分类是否存在
    SoftwareType check = softwareTypeMapper.queryByTname(softwareType);
    if (check != null) {
      return BaseResult.fail("软件分类已经存在");
    }
    // 不存在就添加
    int result = softwareTypeMapper.insert(softwareType);
    return result == 1 ? BaseResult.ok("添加成功") : BaseResult.fail("添加失败");
  }

  @Override
  public BaseDataResult<SoftwareType> queryByKey(Integer id) {
    SoftwareType softwareType = softwareTypeMapper.queryByKey(id);
    if (softwareType == null) {
      return BaseDataResult.fail("软件分类不存在", SoftwareType.class);
    }
    return BaseDataResult.ok(softwareType);
  }

  @Override
  public BaseResult update(SoftwareType softwareType) {
    // 校验名称是否冲突
    SoftwareType check = softwareTypeMapper.queryByTname(softwareType);
    // 系统已有名称 1:操作系统，2:办公软件
    // 修改的信息是 1:操作系统  check为1:操作系统,这个时候是修改是合理
    // 修改的信息是 2:操作系统  check为1:操作系统,这个时候是修改就不合理,因为你尝试修改2号记录为已有的名称
    if (check != null && !softwareType.getStid().equals(check.getStid())) {
      return BaseResult.fail("软件分类名称已经存在");
    }
    int result = softwareTypeMapper.update(softwareType);
    return result == 1 ? BaseResult.ok("修改成功") : BaseResult.fail("修改失败");
  }

  @Override
  public BaseResult delete(Integer id) {
    // 查询该分类下是否还有软件
    Long count = softwareMapper.queryCountByStid(id);
    if (count > 0) {
      return BaseResult.fail("该分类下还有软件，不能删除");
    }
    int i = softwareTypeMapper.delete(id);
    return i == 1 ? BaseResult.ok("删除成功") : BaseResult.fail("删除失败");
  }

  @Override
  public BaseDataResult<PageResult<List<SoftwareType>>> query(SoftwareType type, PageBean pageBean) {
    PageHelper.startPage(pageBean.getPageNumber(), pageBean.getPageSize());
    Page<SoftwareType> page = (Page<SoftwareType>) softwareTypeMapper.query(type);
    pageBean.setTotal(page.getTotal());
    return BaseDataResult.ok(PageResult.instance(pageBean, page.getResult()));
  }

}
